#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <error.h>

#define port 3000

int main()
{
    int sockfd, addr_len, buf_len;
    struct sockaddr_in servaddr, clientaddr;
    addr_len = sizeof(servaddr);
    char buffer[256];
    buf_len = sizeof(buffer);

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        perror("fali to socket: ");
        exit(EXIT_FAILURE);
    }

    bzero(&servaddr, addr_len);

    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if((bind(sockfd, (struct sockaddr*)&servaddr, addr_len)) == -1)
    {
        perror("fail to bind: ");
        exit(EXIT_FAILURE);
    }

    while(1)
    {
        bzero(buffer, buf_len);
        bzero(&clientaddr, addr_len);
        int len = recvfrom(sockfd, buffer, buf_len, 0, (struct sockaddr *)&clientaddr, &addr_len);

        printf("Received a string from client %s:%d, string is: %s\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port), buffer);

        sendto(sockfd, buffer, buf_len, 0, (struct sockaddr*)&clientaddr, addr_len);
    }

    return 0;
}